using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using ThaiLanguageTools.DataStruct;

namespace ThaiLanguageTools.SrcParse
{
    public abstract class DictParser
    {
        protected abstract XDictHeader GetHeader();
        protected abstract XDictEntry ParseEntry(StreamReader sr);

        public virtual XDict Parse(String file)
        {
            XDict dict = new XDict();

            XDictHeader header = GetHeader();
            dict.Headers.Add(header);

            using (StreamReader sr = new StreamReader(file, Utils.ThaiEncoding))
            {
                int i = 0;
                while (true)
                {
                    ++i;

                    XDictEntry entry = ParseEntry(sr);
                    if (entry == null) { break; }

                    dict.AddEntry(entry);

                    if (i % 1000 == 0) { Console.WriteLine(i + ") " + entry.Word); }
                }
                Console.WriteLine("Done " + i + " words found.");
            }
            return dict;
        }

        public static String DetectLanguage(String word)
        {
            if (word != null)
            {
                // 5-char threshold (there may be oddities like parentheses)
                for (int i = 0; i < word.Length; i++)
                {
                    char c = word[i];
                    if (c >= 255) { return Language.Thai; }
                    if (char.IsLetter(c) && c < 255) { return Language.English; }
                }
            }

            return Language.English;
        }

    }
}
